/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-9-22 下午2:39 Created by dwzhang
 */
package com.jade.bss.weixin.controller;

import java.io.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.jade.bss.weixin.api.pay.PayApi;
import com.jade.bss.weixin.api.pay.PayConstants;
import com.jade.bss.weixin.api.pay.protocol.NotifyRequest;
import com.jade.bss.weixin.api.pay.protocol.NotifyResponse;
import com.jade.framework.base.context.ApplicationContextUtils;
import io.swagger.annotations.Api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 微信支付通知接口。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a>
 * @version 1.0 15-9-22 下午2:39
 */
@Controller
@RequestMapping (value = "/weixin/pay")
@Api(value = "微信-支付", description = "支付回调接口", hidden = true)
public class PayController
{
    protected Log log = LogFactory.getLog(PayController.class);
    protected PayApi api = ApplicationContextUtils.getBean("bss_weixinPayApi");

    @RequestMapping (value = "/notify/{appCode}")
    @ResponseBody
    public void notify(@PathVariable String appCode, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        //read notify packet
        NotifyResponse notifyResponse = new NotifyResponse();
        PrintWriter printWriter = response.getWriter();
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        String message = "", line;
        while ((line = br.readLine()) != null) {
            message += line;
        }
        log.info("Receiver a pay notify:" + message);
        //解析报文
        JAXBContext context = JAXBContext.newInstance(NotifyRequest.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        StringReader reader = new StringReader(message);
        NotifyRequest notifyRequest = (NotifyRequest)unmarshaller.unmarshal(reader);
        ;
        if (notifyRequest == null) {
            notifyResponse.setReturnCode(NotifyResponse.FAIL);
            notifyResponse.setReturnMsg(PayConstants.ERR_XML_FORMAT_ERROR);
        }
        else {
            //todo 校验签名
            notifyResponse = api.onNotify(appCode, notifyRequest);
        }
        context = JAXBContext.newInstance(NotifyResponse.class);
        Marshaller marshaller = context.createMarshaller();
        StringWriter writer = new StringWriter();
        marshaller.marshal(notifyResponse, writer);
        String xmlStr = writer.toString();
        printWriter.write(xmlStr);
    }
}
